// pages/mine/mine.js
import { COS_HOST, httpServer } from "../../utils/httpServer";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {
      isLogin: false,
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const {userInfo} = getApp().globalData;
    this.setData({
      userInfo,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    httpServer('POST', 'User', 'GetInfo', {
      openid: wx.getStorageSync('openid')
    })
    .then(res => {
      if (res.result == 'success') {
        let info = res.info;
        Object.assign(info, res.info, {isLogin: true});
        getApp().globalData.userInfo = info;
      }
    })
    .catch(err => {
      console.error(err);
      });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  getPhoneNumber(e) {
    wx.showLoading({
      mask: true,
      title: '加载中',
    });
    const {code, errMsg, errno} = e.detail;
    if (!code) {
      wx.showToast({
        icon: 'none',
        title: '用户拒绝授权',
      })
      return;
    }
    if (errno) {
      wx.showToast({
        icon: 'none',
        title: errMsg,
      })
      return;
    }
    httpServer('POST', 'User', 'GetPhoneNumber', {code})
      .then(phoneRes => {
        if (phoneRes.result == 'success') {
          const phone = phoneRes.info;
          wx.login({
            success: (loginRes) => {
              if (loginRes.code) {
                wx.request({
                  url: `https://api.huacheng-xiaochengxu.com/musoundic/callback.php?code=${loginRes.code}&phone=${phone}`,
                  success: (res) => {
                    if (res.data.result == 'success') {
                      const {openid, phone} = res.data.info;
                      wx.setStorageSync('openid', openid);
                      wx.setStorageSync('phone', phone);
                      this.setData({
                        phone,
                      })
                      this.genUser(openid, phone, -1, -1);
                    }
                  },
                  fail(res) {
                    console.error('error : ', res);
                  },
                  complete() {
                    wx.hideLoading();
                  }
                });
              } else {
                wx.showToast({
                  icon: 'none',
                  title: res.errMsg,
                })
              }
            },
          })
        } else {
          wx.hideLoading({
            complete:() => {
              wx.showToast({
                icon: 'none',
                title: phoneRes.info,
              })
            }
          })
        }
      })
      .catch(err => {
        console.error(err);
        wx.hideLoading();
      })
  },

  genUser(openid, phone, avatar, nickname) {
    httpServer('POST', 'User', 'SaveUser', {
      openid,
      phone,
      avatar,
      nickname,
    }).then(res => {
      if (res.result == 'success') {
        wx.setStorage({
          key: 'openid',
          data: openid,
          success:() => {
            httpServer('POST', 'User', 'GetInfo', {openid}).then(res => {
              wx.hideLoading();
              if (res.result == 'success') {
                let info = {};
                Object.assign(info, res.info, {isLogin: true});
                getApp().globalData.userInfo = info;
                this.setData({
                  userInfo: info,
                  openid,
                });
              } else {
                console.error('set-user-info getinfo error : ', res.info);
                wx.showToast({
                  icon: 'none',
                  title: res.info,
                })
              }
            }).catch(err => {
              console.error(err);
              wx.hideLoading();
            })
          }
        });
      } else {
        wx.hideLoading({
          success: () => {
            wx.showToast({
              icon: 'none',
              title: res.info,
            });
          }
        });
      }
    }).catch(err => {
      console.error(err);
    });
  },

  handleInfo() {
    if (!wx.getStorageSync('openid')) {
      return;
    }
    wx.navigateTo({
      url: '/pages/set-user-info/set-user-info?openid=' + wx.getStorageSync('openid'),
    })
  },

  handleQRCodeTap() {
    if (!wx.getStorageSync('openid')) {
      wx.showToast({
        icon: 'error',
        title: '请先登录',
      })
      return;
    }
    wx.navigateTo({
      url: '/pages/qrcode/qrcode',
    })
  },

  handleActvityTap() {
    if (!wx.getStorageSync('openid')) {
      wx.showToast({
        icon: 'error',
        title: '请先登录',
      })
      return;
    }
    wx.navigateTo({
      url: '/pages/activity/activity',
    })
  }
})